# -*- coding: utf-8 -*-

def cors(self):
    def wrapper():
        response.view = 'generic.json'
        # response.headers['Access-Control-Allow-Origin'] ='*'
        # response.headers['Access-Control-Allow-Methods']='GET, POST,OPTIONS'
        # response.headers['Access-Control-Max-Age']= '3600'
        # response.headers['Access-Control-Allow-Headers']='Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Max-Age, X-Auth-Token, Content-Type, Accept'
        return self()
    return wrapper

@cors
@request.restful()
def get_user_info():
    def GET(*args, **vars):
        return dict(userInfo = db.app_user(*args))
    def POST(*args, **vars):
        import requests
        requestString = 'https://api.weixin.qq.com/sns/jscode2session?appid={APPID}&secret={SECRET}&js_code={JSCODE}&grant_type=authorization_code'.format(
            APPID=vars['APPID'], SECRET=vars['SECRET'], JSCODE=vars['code'])
        r = requests.get(requestString)
        r = r.json()
        openid= r['openid']
        sessionKey = r['session_key']
        encryptedData=vars['userInfo']['encryptedData']
        iv = vars['userInfo']['iv']
        import base64
        import json
        from Crypto.Cipher import AES
        import requests
        class WXBizDataCrypt:
            def __init__(self, appId, sessionKey):
                self.appId = appId
                self.sessionKey = sessionKey
            def decrypt(self, encryptedData, iv):
                # base64 decode
                sessionKey = base64.b64decode(self.sessionKey)
                encryptedData = base64.b64decode(encryptedData)
                iv = base64.b64decode(iv)
                cipher = AES.new(sessionKey, AES.MODE_CBC, iv)
                decrypted = json.loads(self._unpad(cipher.decrypt(encryptedData)))
                if decrypted['watermark']['appid'] != self.appId:
                    raise Exception('Invalid Buffer')
                return decrypted

            def _unpad(self, s):
                return s[:-ord(s[len(s) - 1:])]
        pc = WXBizDataCrypt(vars['APPID'], sessionKey)
        userInfo= pc.decrypt(encryptedData, iv)
        # print userInfo
        userInfo['languages']=userInfo['language']
        db.app_user.update_or_insert(db.app_user.openId == openid, **userInfo)
        return dict(content="1",aa=122,openid=openid,userInfo=db(db.app_user.openId==openid).select().first())
    def OPTIONS(*args, **vars):
        return dict(content="2")
    return locals()

@cors
@request.restful()
def update_user_info():
    def GET(*args, **vars):
        return dict(userInfo = db.app_user(*args))
    def POST(*args, **vars):
        db.app_user.update_or_insert(db.app_user.openId == vars['openId'], **vars)
        return dict(userInfo=db(db.app_user.openId==vars['openId']).select().first())
    def OPTIONS(*args, **vars):
        return dict(content="2")
    return locals()

@cors
@request.restful()
def wxapp_get():
    def GET(*args, **vars):
        count = db.app_pjuser.id.count()
        if vars.has_key('id'):
            return dict(project = db((db.app_project.del_flag =='1')& (db.app_project.openId==db.app_user.openId)& (db.app_project.id==vars['id']) & (db.app_project.tplid==db.app_tpl.id)).select(db.app_project.ALL,db.app_tpl.ALL,db.app_user.ALL,count.with_alias('count'),left=db.app_pjuser.on((db.app_pjuser.del_flag =='1')&(db.app_project.id==db.app_pjuser.pjid)),groupby=db.app_project.id,orderby=~db.app_project.id),
                        pjuser=db((db.app_pjuser.del_flag == '1') & (db.app_pjuser.pjid == vars['id']) & (
                        db.app_pjuser.openId == db.app_user.openId) & (db.app_pjuser.pjid == db.app_project.id) & (
                                  db.app_tpl.id == db.app_project.tplid)).select(orderby=~db.app_pjuser.update_date))
        if vars.has_key('openId'):
            return dict(project = db((db.app_project.del_flag =='1')& (db.app_project.openId==db.app_user.openId)& (db.app_project.openId==vars['openId']) & (db.app_project.tplid==db.app_tpl.id)).select(db.app_project.ALL,db.app_tpl.ALL,db.app_user.ALL,count.with_alias('count'),left=db.app_pjuser.on((db.app_pjuser.del_flag =='1')&(db.app_project.id==db.app_pjuser.pjid)),groupby=db.app_project.id,orderby=~db.app_project.id) )
        if vars.has_key('myopenId'):
            return dict(project = db((db.app_project.del_flag =='1')& (db.app_project.openId==db.app_user.openId)& (db.app_project.id.belongs(db((db.app_pjuser.openId ==vars['myopenId'])&(db.app_pjuser.del_flag=='1'))._select(db.app_pjuser.pjid))) & (db.app_project.tplid==db.app_tpl.id)).select(db.app_project.ALL,db.app_tpl.ALL,db.app_user.ALL,count.with_alias('count'),left=db.app_pjuser.on((db.app_pjuser.del_flag =='1')&(db.app_project.id==db.app_pjuser.pjid)),groupby=db.app_project.id,orderby=~db.app_project.id) )
        return dict(project=db((db.app_project.isopen =='true')&(db.app_project.del_flag =='1')&(db.app_project.openId==db.app_user.openId) ).select(db.app_project.ALL,db.app_user.ALL,count.with_alias('count'),left=db.app_pjuser.on((db.app_pjuser.del_flag =='1')&(db.app_project.id==db.app_pjuser.pjid)),groupby=db.app_project.id,orderby=~db.app_project.id))
    def OPTIONS(*args, **vars):
        return dict(content="2")
    return locals()


@cors
@request.restful()
def wxapp_activity_user():
    def GET(*args, **vars):
        if vars.has_key('id'):
            if vars.has_key('openId'):
                return dict(pjuser=db((db.app_pjuser.del_flag == '1') & (db.app_pjuser.pjid == vars['id']) & (db.app_pjuser.openId == db.app_user.openId) & (db.app_pjuser.openId == vars['openId'])&(db.app_pjuser.pjid==db.app_project.id)&(db.app_tpl.id==db.app_project.tplid)).select(orderby=~db.app_pjuser.update_date))
            return dict(pjuser=db((db.app_pjuser.del_flag =='1')&(db.app_pjuser.pjid==vars['id'])&(db.app_pjuser.openId==db.app_user.openId)&(db.app_pjuser.pjid==db.app_project.id)&(db.app_tpl.id==db.app_project.tplid)).select(orderby=~db.app_pjuser.update_date))
        return dict(pjuser = db((db.app_pjuser.del_flag =='1')&(db.app_pjuser.openId==db.app_user.openId)&(db.app_pjuser.pjid==db.app_project.id)&(db.app_tpl.id==db.app_project.tplid)).select(orderby=~db.app_pjuser.update_date))
    def OPTIONS(*args, **vars):
        return dict(content="2")
    return locals()

@cors
@request.restful()
def wxapp_baomin():
    def POST(*args, **vars):
        db.app_pjuser.update_or_insert((db.app_pjuser.del_flag =='1')& (db.app_pjuser.pjid == vars['pjid'])&(db.app_pjuser.openId == vars['openId']),**vars)
        sendmessage(**vars)
        return dict(pjuser=db((db.app_pjuser.del_flag=='1')&(db.app_pjuser.openId==db.app_user.openId)&(db.app_pjuser.pjid==vars['pjid'])).select())
    def OPTIONS(*args, **vars):
        return dict(content="2")
    return locals()

@cors
@request.restful()
def wxapp_get_tpl():
    def GET(*args, **vars):
        tpl=db(db.app_tpl).select()
        return dict(tpl=tpl)
    def POST(*args, **vars):
        print 2
        return dict(content="1",aa=122,openid="a123")
    def OPTIONS(*args, **vars):
        return dict(content="2")
    return locals()

@cors
@request.restful()
def wxapp_add():
    def GET(*args, **vars):
        return dict(content="1")
    def POST(*args, **vars):
        tm=vars['templ']
        for i, row, in enumerate(tm['templ']):
            tm['templ'][i]['keyname']="fd"+str(i+1).zfill(3)
            tm['templ'][i]['typevalue']=tm['templ'][i]['typevalue'].split(",")
        import json
        vars['templ']=json.dumps(tm)
        if vars.has_key('id'):
            return dict(db((db.app_project.id == vars['id']) & (db.app_project.openId == vars['openId'])).validate_and_update(**vars))
        return dict(db.app_project.validate_and_insert(**vars))

    def OPTIONS(*args, **vars):
        return dict(content="2")
    return locals()

@cors
@request.restful()
def wxapp_update_tpl_num():
    def GET(*args, **vars):
        tpl=db.app_tpl(*args)
        tpl.total=int(tpl.total)+1
        tpl.update_record()
        return dict(content="2")
    def OPTIONS(*args, **vars):
        return dict(content="2")
    return locals()

@cors
@request.restful()
def wxapp_sendmail():
    def GET(*args, **vars):
        # openId id
        falg="false"
        project_user = db((db.app_project.del_flag =='1')&(db.app_project.id == vars['id'])&(db.app_project.openId==db.app_user.openId)&(db.app_tpl.id==db.app_project.tplid) ).select().first()
        subject='数据报告 '+project_user['app_project'].title+':'+project_user['app_project'].startTime+'至'+project_user['app_project'].endTime
        import json
        tpl=json.loads(project_user['app_project'].templ)
        pjusers = db((db.app_pjuser.del_flag =='1')&(db.app_pjuser.pjid== vars['id'])&(db.app_pjuser.openId==db.app_user.openId)).select()
        mail_body ='<html><div><br></div><div><includetail>' \
                   '<style>.x0{background:# C5D9F1;}.x1{background:#EBF1DE;} .x168{background:#00B0F0;}.red{ color:#F00;}</style>' \
                   '<table border="0" cellpadding="3" cellspacing="0" width="auto" style="text-align:center;">' \
                   '<tbody><tr><td colspan="'+str(len(tpl['templ'])+2)+'">'+project_user['app_project'].title+'</td></tr>' \
                   '<tr class="x168"> <td>序号</td><td>微信名称</td>'
        for tps in tpl['templ']:
            mail_body=mail_body+'<td>'+tps['name'].encode('utf-8')+'</td>'
        mail_body = mail_body +'</tr>'
        for i, pjuser, in enumerate(pjusers):
            if i%2:
                mail_body = mail_body+  '<tr class="x0">'
            else:
                mail_body = mail_body + '<tr class="x1">'
            name=pjuser.app_user.name
            if not name:
                name=pjuser.app_pjuser.nickName
            mail_body = mail_body + '<td>'+str(i)+'</td><td>'+name+'</td>'
            for tps in tpl['templ']:
                if tps['type']=='2':
                    mail_body = mail_body + '<td>' + tps['typevalue'][int(pjuser.app_pjuser[tps['keyname']])].encode('utf-8') + '</td>'
                else:
                    mail_body = mail_body + '<td>' + pjuser.app_pjuser[tps['keyname']] + '</td>'
            mail_body = mail_body + '</tr>'
            # '<td>'+pjuser.fd001+'</td><td>'+pjuser.fd002+'</td><td>'+pjuser.fd003+'</td><td>'+pjuser.fd004+'</td><td>'+pjuser.fd005+'</td><td>'+pjuser.fd006+'</td></tr>'
        mail_body = mail_body + "</tbody></table></includetail></div></html>"

        if project_user['app_user'].mail:
            falg = mail.send(project_user['app_user'].mail, subject, mail_body)  # lbaorg@sina.com
        return dict(code=falg)
    def OPTIONS(*args, **vars):
        return dict(content="2")
    return locals()

@cors
@request.restful()
def wxapp_delete():
    def GET(*args, **vars):
        count = db.app_pjuser.id.count()
        if vars.has_key('projectid'):
            db(db.app_project.id == vars['projectid']).update(del_flag = 0)
            return dict(project = db((db.app_project.del_flag =='1')& (db.app_project.openId==db.app_user.openId)& (db.app_project.openId==vars['openId']) & (db.app_project.tplid==db.app_tpl.id)).select(db.app_project.ALL,db.app_tpl.ALL,db.app_user.ALL,count.with_alias('count'),left=db.app_pjuser.on((db.app_pjuser.del_flag =='1')&(db.app_project.id==db.app_pjuser.pjid)),groupby=db.app_project.id,orderby=~db.app_project.id) )
        if vars.has_key('pjuserid'):
            db(db.app_pjuser.id == vars['pjuserid']).update(del_flag=0)
            return dict(pjuser=db((db.app_pjuser.del_flag =='1')&(db.app_pjuser.pjid==vars['pjid'])&(db.app_pjuser.openId==db.app_user.openId)).select(orderby=~db.app_pjuser.update_date))
        return dict(code="false")
    def OPTIONS(*args, **vars):
        return dict(content="2")
    return locals()


@cors
@request.restful()
def gettoken():
    def GET(*args, **vars):
        aa=get_token()
        return dict(content=aa)
    return locals()

def get_token():
    appid = 'wx91565ea9a81ea7fc'
    appsecret='6af8514e6c09757f046e6889496ddf6d'
    import datetime
    rowtoken=db(db.app_token).select().first()
    if((rowtoken is not None ) and (rowtoken.expires_in>datetime.datetime.now())):
        return rowtoken.access_token
    else:
        import requests
        requestString = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}'.format(
            APPID=appid, APPSECRET=appsecret)
        r = requests.get(requestString)
        r = r.json()
        token = r['access_token']
        expires_in=r['expires_in']
        # token = '1jnP4rG8CpyjjeaB_k9t5E29b8-LJ-5vgvhU_sA8EyhTFjyqhQAqGOupBBsSyBlzz119Q_AxlQskKvMBJe0uHNR5_YKq53NyqCd9FhDIl1N8uY2wfHI3c_izBuZd7_61ZT0b8t2mFSnATCz7oDMUiAGAPYG'
        # expires_in ='7200'
        dataex=datetime.datetime.now()+datetime.timedelta(seconds=int(expires_in))
        db.app_token.update_or_insert((db.app_token.appid == appid) & (db.app_token.appsecret == appsecret),appid=appid,appsecret=appsecret,access_token=token,expires_in=dataex )
    return token

def sendmessage(**vars):
    openid=vars['openId']
    formid=vars['formId']
    template_id='hk20gxtnvbnbF4n6q79JREqhvpShwhUNClid-6B78pc'
    project_user = db((db.app_project.id == vars['pjid'])&(db.app_project.openId == db.app_user.openId) & (db.app_tpl.id == db.app_project.tplid)).select().first()
    pjusers = db((db.app_pjuser.del_flag == '1') & (db.app_pjuser.openId == openid)).select().first()
    payload = {"touser": openid,  "template_id": template_id, "page": "pages/all/all","form_id":formid,"data": {
      "keyword1": {"value": project_user.app_project.title,"color": "#173177"},
      "keyword2": {"value": "上报人 12:30","color": "#173177"},
      "keyword3": {"value": "详情","color": "#173177"}
    },"emphasis_keyword": "keyword1.DATA"}
    import requests
    requestString = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={ACCESS_TOKEN}'.format(
        ACCESS_TOKEN=get_token())
    r = requests.post(requestString, data=payload)
    print(r.text)

    return 1

